//
//  UIButton+YM_FixMultiClick.m
//  OAX
//
//  Created by XuHongBin on 2018/7/27.
//  Copyright © 2018年 YeMing. All rights reserved.
//

#import "UIButton+YM_FixMultiClick.h"
#import <objc/runtime.h>

@implementation UIControl (YM_FixMultiClick)
// 因category不能添加属性，只能通过关联对象的方式。
@dynamic ym_acceptEventTime;
@dynamic ym_acceptEventInterval;
- (NSTimeInterval)ym_acceptEventInterval {
    NSNumber *number = objc_getAssociatedObject(self, _cmd);
    if (!number) {
        [self setYm_acceptEventInterval:0.2];
        return 0.2;
    }
    return  [number doubleValue];
}

- (void)setYm_acceptEventInterval:(NSTimeInterval)ym_acceptEventInterval {
    objc_setAssociatedObject(self, @selector(ym_acceptEventInterval), @(ym_acceptEventInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSTimeInterval)ym_acceptEventTime {
    NSNumber *number = objc_getAssociatedObject(self, _cmd);
    if (number == nil) {
        return 0;
    }
    return [number doubleValue];
}

- (void)setYm_acceptEventTime:(NSTimeInterval)ym_acceptEventTime {
    objc_setAssociatedObject(self, @selector(ym_acceptEventTime), @(ym_acceptEventTime), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}


// 在load时执行hook
+ (void)load {
    Method before   = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:));
    Method after    = class_getInstanceMethod(self, @selector(cs_sendAction:to:forEvent:));
    method_exchangeImplementations(before, after);
}

- (void)cs_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
    if ([self __isIgnore]) {
        [self cs_sendAction:action to:target forEvent:event];
        return;
    }
    
    NSTimeInterval ym_acceptEventTime = [self ym_acceptEventTime];
    NSTimeInterval ym_acceptEventInterval = [self ym_acceptEventInterval];
    if ([NSDate date].timeIntervalSince1970 -  ym_acceptEventTime < ym_acceptEventInterval) {
        return;
    }
    
    if (ym_acceptEventInterval > 0) {
        self.ym_acceptEventTime = [NSDate date].timeIntervalSince1970;
    }
    [self cs_sendAction:action to:target forEvent:event];
}

- (BOOL)__isIgnore
{
    if ([self isImagePicking]){
        return YES;
    }
    if ([self isKindOfClass:[UIButton class]]) {
        return NO;
    }
    return YES;
}
- (BOOL)isImagePicking{
    UIResponder *temp = self;
    while (temp) {
        temp = [temp nextResponder];
        if ([temp isKindOfClass:[UIImagePickerController class]]){
            return true;
        }
    }
    return false;
}
@end
